"""
主题: 使用生成器代替线程
问题: 你想使用生成器（协程）替代系统线程来实现并发。这个有时又被称为用户级线程或绿色线程。
提示 : 
"""

'''使用简单的 yield 语句的生成器函数'''
# Two simple generator functions
def countdown(n):
    print("countdown[{}] is starting ".format(n))
    while n > 0:
        print('T-minus', n)
        yield
        n -= 1
    print('Blastoff!')

def countup(n):
    print("countup[{}] is starting ".format(n))
    x = 0
    while x < n:
        print('Counting up', x)
        yield
        x += 1

'''简单任务调度器的代码'''

from collections import deque

class TaskScheduler:
    def __init__(self):
        self._task_queue = deque()

    def new_task(self, task):
        '''
        Admit a newly started task to the scheduler
        '''
        self._task_queue.append(task)

    def run(self):
        '''
        Run until there are no more tasks
        '''
        while self._task_queue:
            task = self._task_queue.popleft()
            try:
                # Run until the next yield statement
                next(task)
                self._task_queue.append(task)
            except StopIteration as e:
                # Generator is no longer executing
                print(e)

def recipe1():
    sched = TaskScheduler()
    sched.new_task(countdown(10))
    sched.new_task(countdown(5))
    sched.new_task(countup(15))
    sched.run()


def main():
    print('recipe1'.center(20, '*'))
    recipe1()


if __name__ == '__main__':
    main()   
